<?php

namespace App\Http\Controllers\Api\Customer;

use App\Models\Bill\Bill;
use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Models\Customer\Customer;  //会员主表

use App\Models\Customer\CustRank;  //会员等级表

use App\Models\Wx\WxCustomer; //微信会员表

use App\Models\Wx\WxAppletCustomer; //微信小程序会员表

use App\Models\ConfigureFunction; //功能配置表

use App\Models\SysSeqno; //流水号记录表

use App\Models\Customer\ActivityCodePool; //活动码池子表

use App\Service\WdhService;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class CustomerController extends Controller
{

    /**
     * 获取会员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request)
    {

        $session_id = $request->input('session_id');
        $card_num = $request->input('card_num', 0);
        $balance = $request->input('balance', 0);
        $points = $request->input('points', 0);
        $order = $request->input('order', 0);
        if (empty($session_id)) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：session_id']);
        }

        //获取客户号
        $pcustID = 0;
        $wx_applet_info = Redis::get('WX_APPLET_USER_' . $session_id);
        if ( $wx_applet_info ) {
            $wx_applet_info =  json_decode($wx_applet_info, true);
            if (isset($wx_applet_info['pcustID']) && ebsig_is_int($wx_applet_info['pcustID'])) {
                $pcustID = $wx_applet_info['pcustID'];
            } else {
                return response()->json(['code' => 100001, 'message' => '会员未登录']);
            }
        }

        //查询会员信息
        $customer = Customer::select('pcustID', 'custID', 'cardNo', 'mobile')->find($pcustID);
        if ( !$customer ) {
            return response()->json(['code' => 100002, 'message' => '会员不存在']);
        }

        //昵称
        $nick_name = $customer['custID'];
        if (!empty($customer['nickName'])) {
            $nick_name = $customer['nickName'];
        }

        //头像
        $head_pic = '';
        if (!empty($customer['head_pic']) && $customer['head_pic'] != 'default_user.gif') {
            $head_pic = $customer['head_pic'];
        }

        $openId = '';

        //获取微信粉丝的头像和昵称
        $wx_applet_customer = WxCustomer::where(['pcustID' => $pcustID])->first();
        if ($wx_applet_customer) {
            $nick_name = $wx_applet_customer->nickName;
            $head_pic = $wx_applet_customer->headPic;
            $openId = $wx_applet_customer->openId;
        }

        /**
         * ========================================
         * 查询账户余额和积分
         * ========================================
         */
        $args_data = [
            'cardNo' => $customer['cardNo'],
            'pcustID' => $pcustID,
            'custID' => $customer['custID'],
            'openId' => $openId ? $openId : $customer['custID']
        ];

        //查询账户积分
        if ($points == 1) {
            $points = WdhService::points( $args_data );
        }

        //查询账户余额
        if ($balance == 1) {
            $balance = WdhService::balance( $args_data );
        }

        /**
         * ========================================
         * 查询未使用卡券数量
         * ========================================
         */
        if ( $card_num == 1 ) {
            $card_num = ActivityCodePool::where([['pcustID', $pcustID], ['code_status', 1], ['code_end_time', '>', Carbon::now()]])->count();
        }

        $order_unpaid = 0; //未付款订单数
        $order_not_shipped = 0; //未发货订单数
        $order_not_received = 0; //未收货订单数
        $order_not_comment = 0; //未评论订单数
        $order_return = 0; //退货退款订单数
        if ($order == 1) {

            $order_unpaid = Bill::where([['pcustID', $pcustID], ['bill_status', '<>', 5], ['pay_type', '<>', 1]])->whereIn('pay_status', [0, 2])->count();
            $order_not_shipped = Bill::where([['pcustID', $pcustID], ['bill_status', 1]])->count();
            $order_not_received = Bill::where('pcustID', $pcustID)->whereIn('bill_status', [2, 3])->count();
            $order_not_comment = Bill::where([['pcustID', $pcustID], ['is_comment', 0], ['bill_status', 4]])->count();
            $order_return = Bill::where('pcustID', $pcustID)->where(function ($query) {
                $query->where('bill_return_status', '>', 0)->orWhere('bill_refund_status', '>', 0);
            })->count();

        }

        /**
         * ========================================
         * 查询积分设置
         * ========================================
         */
        $points_setting = ConfigureFunction::getConfigureField(2, 'show_name', '');
        if ($points_setting) {
            $points_show_name = $points_setting;
        } else {
            $points_show_name = '积分';
        }

        return response()->json([
            'code' => 200,
            'message' => 'ok',
            'data' => [
                'nick_name' => app_to_string($nick_name),
                'custID' => app_to_string($customer['custID']),
                'mobile' => app_to_string($customer['mobile']),
                'card_no' => app_to_string($customer['cardNo']),
                'rankName' => app_to_string($customer['rankName']),
                'head_pic' => app_to_string($head_pic),
                'points' => $points,
                'balance'=> $balance,
                'card_num' => $card_num,
                'points_show_name' => $points_show_name,
                'order_unpaid' => $order_unpaid,
                'order_not_shipped' => $order_not_shipped,
                'order_not_received' => $order_not_received,
                'order_not_comment' => $order_not_comment,
                'order_return' => $order_return,
            ]
        ]);

    }

    /**
     * 根据手机号查询会员是否存在
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function checkMobile( Request $request )
    {

        //手机号
        $mobile = $request->input('mobile');

        if ( empty( $mobile ) ) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：mobile']);
        }

        //获取发送短信次数
        $sms_num = redisTransformation(Redis::get('SMS_SEND_' .$mobile));
        if ( empty( $sms_num ) ) {
            $sms_num = 0;
        }

        //查询会员信息
        $customer_data = Customer::select('pcustID')->where(['custID'=> $mobile])->first();
        if ( !$customer_data ) {

            $customer_data = Customer::select('pcustID')->where(['mobile'=> $mobile])->first();
            
            if ( !$customer_data ) {
                return response()->json([
                    'code' => 200,
                    'message' => 'ok',
                    'data' =>[
                        'sms_num'=>$sms_num,
                        'is_register' => 0
                    ]
                ]);
            }
        }

        return response()->json([
            'code' => 200,
            'message' =>'ok',
            'data' =>[
                'sms_num'=>$sms_num,
                'is_register'=>1,
            ]
        ]);

    }

}